package com.example.art_cloud_backend.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.example.art_cloud_backend.config.CosClientConfig;
import com.example.art_cloud_backend.exception.BusinessException;
import com.example.art_cloud_backend.exception.ErrorCode;
import com.example.art_cloud_backend.exception.ThrowUtils;
import com.example.art_cloud_backend.manager.CosManager;
import com.example.art_cloud_backend.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @author caiya
 * @description 图片上传模板方法类
 * @version 1.0
 * @deprecated 已废弃，改为使用 upload 包的模板方法优化
 */
@Deprecated
@Slf4j
public abstract class PictureUploadTemplate {
    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 校验方法
     */
    public abstract void validatePicture(Object inputSource);

    /**
     * 获取文件名称
     */
    public abstract String getOriginFilename(Object inputSource);

    /**
     * 处理输入源并生成本地临时文件
     */
    public abstract void processFile(Object inputSource, File file) throws Exception;

    /**
     * 模板方法：定义上传流程
     */
    public UploadPictureResult uploadPictureTemplate(Object inputSource, String uploadPathPrefix) {
        // 1. 校验图片
        validatePicture(inputSource);

        // 2. 图片上传地址
        String uuid = RandomUtil.randomString(16);
        // 原始文件名称
        String originFilename = getOriginFilename(inputSource);
        // 文件后缀
        String suffix = originFilename.substring(originFilename.lastIndexOf(".") + 1);
        // 上传文件名称
        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, suffix);
        // 上传路径
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);


        File file = null;
        try {
            // 创建临时文件
            file = File.createTempFile(uploadPath, null);
            // 处理文件来源（本地或URL）
            processFile(inputSource, file);
            // 上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            // 解析结果
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 获取规则
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if (CollUtil.isNotEmpty(objectList)) {
                // 如果存在规则数组，说明有压缩操作，获取压缩后的图片信息
                CIObject compressObject = objectList.get(0);
                CIObject thumbnailObject = compressObject;
                if (objectList.size() > 1) {
                    thumbnailObject = objectList.get(1);
                    // 封装压缩图返回结果
                    return buildResult(originFilename, compressObject, thumbnailObject);
                }

                return buildResult(originFilename, compressObject, thumbnailObject);
            }
            return buildResult(originFilename, uploadPath, file, imageInfo);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "测试上传文件失败");
        } finally {
            // 清理临时文件
            deleteTmpFile(file);
        }
    }

    /**
     * 构建上传结果（原始图片）
     * @param originFilename 原始文件名
     * @param uploadPath 上传路径
     * @param file 本地临时文件
     * @param imageInfo 图片信息
     * @return 上传结果
     */
    private UploadPictureResult buildResult(String originFilename, String uploadPath, File file, ImageInfo imageInfo) {
        // 计算宽高
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        // 比例
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        // 封装结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        uploadPictureResult.setPicName(originFilename);
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        return uploadPictureResult;
    }

    /**
     * 构建上传结果（压缩后的图片）
     * @param originFilename 原始文件名
     * @param ciObject 图片信息
     * @return 上传结果
     */
    private UploadPictureResult buildResult(String originFilename, CIObject ciObject, CIObject thumbnailObject) {
        // 计算宽高
        int picWidth = ciObject.getWidth();
        int picHeight = ciObject.getHeight();
        // 比例
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        // 封装结果
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setPicName(originFilename);
        uploadPictureResult.setPicSize(ciObject.getSize().longValue());
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(ciObject.getFormat());

        // 设置图片为压缩后的地址
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + ciObject.getKey());
        // 设置缩略图地址
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailObject.getKey());
        return uploadPictureResult;
    }


    /**
     * 删除临时文件
     *
     * @param file 临时文件
     */
    private static void deleteTmpFile(File file) {
        if (file == null) {
            return;
        }
        boolean deleteRes = file.delete();
        log.error("删除文件失败 filepath = {}", file.getAbsolutePath());
        ThrowUtils.throwIf(!deleteRes, ErrorCode.SYSTEM_ERROR, "文件删除失败");
    }
}
